//请求状态,数据封装

import 'network_code.dart';

class Resource<T> {
  final Status status;
  final String message;
  final int code;
  final T? data;

  Resource(this.status, this.code, this.message, this.data);

  static success<T>(T? data, {String? message}) =>
      Resource(Status.success, NetworkCode.success, message ?? '', data);

  static error<T>(int code, String msg) =>
      Resource<T>(Status.error, code, msg, null);

  @override
  String toString() {
    return 'Result{status: $status, message: $message, data: $data}';
  }

  bool isSuccess() {
    return status == Status.success;
  }

  Resource<R> flatMap<R>(R Function(T? data) transform) {
    if (status == Status.success && data != null) {
      return Resource.success(transform(data));
    }
    if (status == Status.success) {
      return Resource.success<R>(null);
    }
    return Resource.error<R>(code, message);
  }

  R? map<R>(R Function(T? data) transform) {
    if (status == Status.success && data != null) {
      // print('data1234===>$data');
      return transform(data);
    }
    return null;
  }

  List<R> mapList<R>(R Function(T? data) transform) {
    if (status == Status.success && data != null) {
      // print('data2===>$data');
      if (data is List) {
        return (data as List).map((e) => transform(e)).toList();
      }
      return [];
    }
    return [];
  }
}

enum Status { success, error }
